<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="500px"
    @close="close"
  >
    <el-form ref="formRef" label-width="120px" :model="form" :rules="rules">
      <el-form-item label="字典分类" prop="code">
        <el-input v-model="form.code" placeholder="请输入字典分类值" />
      </el-form-item>
      <el-form-item label="字典分类名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入字典分类名称" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { addDictType, updateDictType } from '@/api/dictionaryManagement'
  export default defineComponent({
    name: 'DictionaryManagementEdit',
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')

      const state = reactive({
        formRef: null,
        form: {
          id: '',
          code: '',
          name: '',
        },
        rules: {
          code: [{ required: true, trigger: 'blur', message: '请输入名称' }],
          name: [
            { required: true, trigger: 'blur', message: '请输入字典分类名称' },
          ],
        },
        title: '',
        dialogFormVisible: false,
      })
      const showEdit = (row) => {
        if (row) {
          state.title = '编辑字典分类'
          state.form = row.data
        } else {
          state.title = '添加字典分类'
        }
        state.dialogFormVisible = true
      }
      const close = () => {
        state.form = {
          id: null,
          code: '',
          name: '',
        }
        state.dialogFormVisible = false
      }
      const add = async () => {
        try {
          const { msg } = await addDictType(state.form)
          $baseMessage(msg, 'success', 'vab-hey-message-success')
          emit('fetch-data')
          close()
        } catch (e) {
          console.error(e)
        }
      }
      const edit = async () => {
        try {
          const { msg } = await updateDictType(state.form)
          $baseMessage(msg, 'success', 'vab-hey-message-success')
          emit('fetch-data')
          close()
        } catch (e) {
          console.error(e)
        }
      }
      const save = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            if (state.form.id) {
              edit()
            } else {
              add()
            }
          }
        })
      }

      return {
        ...toRefs(state),
        showEdit,
        close,
        save,
      }
    },
  })
</script>
